package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.NcgDeviceWatch;
import com.sqx.modules.health.entity.Record;
import com.sqx.modules.health.entity.Recordset;
import com.sqx.modules.health.service.INcgDeviceWatchService;
import com.sqx.modules.health.service.IRecordService;
import com.sqx.modules.health.service.IRecordsetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hsx
 * @since 2022-07-23
 */

@Api(value = "", tags = "", description = "")
@RestController
@RequestMapping("/health/romatdata")
public class DataController {
    @Autowired
    private IRecordService recordService;
    @Autowired
    private INcgDeviceWatchService watchService;
    @Autowired
    private IRecordsetService recordsetService;

    // 动态血压患者推送
    @PostMapping("/sendpat")
    @ApiOperation(value = "动态血压患者推送", notes = "动态血压患者推送")
    public Result sendPat(@RequestBody JSONObject jsonObject){

        watchService.editBinding(jsonObject.get("uid"), jsonObject.get("doctorid"), jsonObject.get("imei"));
        saveRecords(jsonObject);
        return Result.success(recordService.sendPat(jsonObject));

    }

    private void saveRecords(JSONObject jsonObject) {
        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
                .eq(ObjectUtil.isNotEmpty(jsonObject.getString("imei")), "imei", jsonObject.getString("imei"));

        NcgDeviceWatch watch = watchService.getOne(wrapper);
        Recordset recordset = new Recordset();
        recordset.setImei(jsonObject.getString("imei"));
        recordset.setUid(jsonObject.getLong("uid"));
        recordset.setDocid(jsonObject.getLong("doctorid"));
//        recordset.setStatus(watch.getStatus());
        recordset.setStatus(0);
//        recordset.setDevicename(watch.getDevicename());
        recordset.setStartdate(LocalDateTime.now());
        recordset.setDevicetype(Integer.valueOf(watch.getType()));
        recordsetService.saveOrUpdate(recordset);

    }

    // 远程动态血压报告获取
    @PostMapping("/downLoadReoprt")
    @ApiOperation(value = "远程动态血压报告获取", notes = "远程动态血压报告获取")
    public Result downLoadReoprt(@RequestBody Record record) throws MalformedURLException {
        return Result.success("文件位置：" + recordService.downLoadReoprt(record));
    }
}

